<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div
        class="cart-body"
        v-for="cartInfoItem in cartInfoList"
        :key="cartInfoItem.id"
      >
        <ul class="cart-list">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="cartInfoItem.isChecked == 1"
              @change="updateChecked(cartInfoItem, $event)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfoItem.imgUrl" />
            <div class="item-msg">
              {{ cartInfoItem.skuName }}
            </div>
          </li>
          <li class="cart-list-con3">
            <span class="price">{{ cartInfoItem.skuPrice }}</span>
          </li>
          <li class="cart-list-con4">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="handler('minus', -1, cartInfoItem)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfoItem.skuNum"
              @change="handler('change', $event.target.value - 0, cartInfoItem)"
              minnum="1"
              class="itxt"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="handler('add', 1, cartInfoItem)"
              >+</a
            >
          </li>
          <li class="cart-list-con5">
            <span class="sum">{{
              cartInfoItem.skuNum * cartInfoItem.skuPrice
            }}</span>
          </li>
          <li class="cart-list-con6">
            <a
              href="#none"
              class="sindelet"
              @click="deleteCartById(cartInfoItem)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          :checked="isAllChecked && cartInfoList.length !== 0"
          @change="updateCheckedAll"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="deleteChecked">删除选中的商品</a>
        <a>移到我的关注</a>
        <a>清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ checkedNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" @click="$router.push('/trade')">结算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
// 引入lodash: 是把lodash全部封装好的函数全部引入
// 按需引入，只引入节流函数
import throttle from "lodash/throttle";

export default {
  name: "ShopCart",
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.$store.dispatch("getCartList");
    },
    // 为了防止快速连续点击数量文本框出现-1等异常情况
    // 需要使用throttle节流(1000ms间隔内的操作不算数)
    // 数量修改
    handler: throttle(async function (type, disNum, cartInfoItem) {
      switch (type) {
        case "add":
          disNum = 1;
          break;
        case "minus":
          disNum = cartInfoItem.skuNum > 1 ? -1 : 0;
          break;
        case "change":
          if (isNaN(disNum) || disNum < 1) {
            disNum = 0;
          } else {
            disNum = parseInt(disNum) - cartInfoItem.skuNum;
          }
          // disNum = (isNaN(disNum) || disNum < 1) ? 0:parseInt(disNum) - cart.skuNum
          break;
      }
      try {
        // eslint-disable-next-line vue/no-async-in-computed-properties
        // 派发 addOrUpdateShopCart 修改传递数据，但是页面不会发生变化
        await this.$store.dispatch("addOrUpdateShopCart", {
          skuId: cartInfoItem.skuId,
          skuNum: disNum,
        });
        // 根据改变的数值改变购物车列表
        // this.$store.dispatch("getCartList");
        this.getData();
      } catch (error) {
        alert(error);
      }
    }, 1000),
    // 删除购物车产品
    deleteCartById: throttle(async function (cartInfoItem) {
      try {
        await this.$store.dispatch("deleteCartBySkuId", cartInfoItem.skuId);
        // 如果删除请求成功，再次发请求刷新购物车
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    }, 1000),
    // 更新购物车商品是否选中
    async updateChecked(cartInfoItem, event) {
      try {
        let checked = event.target.checked ? "1" : "0";
        await this.$store.dispatch("updateCheckedById", {
          skuId: cartInfoItem.skuId,
          isChecked: checked,
        });
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    // 删除选中的商品
    async deleteChecked() {
      try {
        await this.$store.dispatch("deleteChecked");
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
    // 修改全选
    async updateCheckedAll(event) {
      try {
        let isChecked = event.target.checked ? "1" : "0";
        await this.$store.dispatch("updateCheckedAll", isChecked);
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },
  },
  computed: {
    ...mapGetters(["cartList"]),
    cartInfoList() {
      return this.cartList.cartInfoList || [];
    },
    totalPrice() {
      let sum = 0;
      this.cartInfoList.forEach((item) => {
        if (item.isChecked) sum += item.skuNum * item.skuPrice;
      });
      return sum;
    },
    isAllChecked() {
      return this.cartInfoList.every((item) => {
        return item.isChecked >= 1 || item.isChecked == "true";
      });
    },
    checkedNum() {
      let num = 0;
      this.cartInfoList.forEach((item) => {
        item.isChecked ? num++ : "";
      });
      return num;
    },
    // sumPrice(){
    //   this.cartInfoList.forEach((item) => {
    //     item.isChecked ?
    //   });
    //   return 0
    // },
  },
};
</script>

<style lang='less'>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 5%;
          height: 82px;
          line-height: 82px;
        }
        .cart-list-con2 {
          width: 45%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            margin: 0 10px;
            width: 400px;
            height: 82px;
            line-height: 82px;
          }
        }
        .cart-list-con3 {
          width: 10%;
          height: 82px;
          line-height: 82px;
        }
        .cart-list-con4 {
          width: 16%;
          margin: 16px 0px;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 20px;
            text-align: center;
            height: 50px;
            line-height: 52px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 50px;
            float: left;
            text-align: center;
            font-size: 14px;
          }
          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 20px;
            text-align: center;
            height: 50px;
            line-height: 52px;
          }
        }
        .cart-list-con5 {
          width: 11.5%;
          .sum {
            font-size: 14px;
            height: 82px;
            line-height: 82px;
          }
        }
        .cart-list-con6 {
          width: 12.5%;
          margin: 25px 0px;
          a {
            width: 45%;
            color: #666;
            display: block;
            float: left;
            cursor: pointer;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;
    height: 52px;
    line-height: 52px;
    .select-all {
      padding: 0px 10px;
      overflow: hidden;
      float: left;
      span {
        padding-left: 5px;
      }
      input {
        vertical-align: middle;
      }
    }
    .option {
      padding: 0px 10px;
      overflow: hidden;
      float: left;
      a {
        float: left;
        padding: 0 10px;
        color: #666;
        cursor: pointer;
      }
    }
    .money-box {
      float: right;
      .chosed {
        float: left;
        padding: 0 10px;
      }
      .sumprice {
        width: 200px;
        float: left;
        padding: 0 10px;
        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }
      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          cursor: pointer;
        }
      }
    }
  }
}
</style>